﻿/*
 * Created by SharpDevelop.
 * User: MyWife
 * Date: 5/18/2008
 * Time: 11:22 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
 using System;
 
 namespace popLib{
	 public static class DateTimeLib{

        public static DateTime NullDateTime { get { return new DateTime(1900, 1, 1, 0, 0, 0).Date; } }

	 	//get date only
		public static DateTime getDate()
		{
			return new DateTime( DateTime.Now.Date.Year, DateTime.Now.Date.Month, DateTime.Now.Date.Day );
		}
	
		//get date and time
		public static DateTime getDateTime()
		{
			return DateTime.Now;
		}
	
		//get string date with form as "MM/dd/yyyy"
		public static string getDateString()
		{
			return DateTime.Now.Date.Month +"/"+ DateTime.Now.Date.Day +"/"+ DateTime.Now.Date.Year;
		}
	
		//get string time with form as "hh.mm"
		public static string getTimeString()
		{
			int min = DateTime.Now.Minute;
			int hou = DateTime.Now.Hour;
			if(min < 10) return hou +".0"+ min;
			return hou +"."+ min;
		}
		
		
		/// <summary>
		/// get date from string with form as "MM/dd/yyyy"
		/// if incorrect input -> return current date
		/// </summary>
		/// <param name="val"></param>
		/// <returns></returns>
		public static DateTime GetDateFromString(string val)
		{
			if(val.IndexOf("/") == val.LastIndexOf("/")) return getDate();
			string[] str = val.Split('/');
			int mon = Convert.ToInt16(str[0]);
			int day = Convert.ToInt16(str[1]);
			int yea = Convert.ToInt16(str[2]);
			return new DateTime(yea,mon,day);
		}
				
		/// <summary>
		/// receive time string like "hh.mm"
		/// fix time to correct form
		/// ex  1.65  -> 2.05
		/// </summary>
		/// <param name="time"></param>
		/// <returns></returns>
		public static string fixTimeValue(string time)
		{			
			if(time.Trim() == "0") return "";
			if( time != null && time.Trim().Length > 0 && time.IndexOf(".") == -1) return time+".00";
			if(time.IndexOf(".")>=0)
			{
				string[] str = ("0"+time).Split('.');
				int hou = Convert.ToInt16(str[0]);
				int min = Convert.ToInt16(str[1]);
				if( str[1].Trim().Length == 1 && min >= 6 && min < 10)
					time = (hou + 1) + "." + (min - 6);
	
				if( min >= 60 && min < 70)
					time = (hou + 1) + ".0" + ( min - 60);
				if( min >= 60 && min >= 70)
					time = (hou + 1) + "." + ( min - 60);
			}
			if(time.IndexOf(".") == time.Length-2) return time+"0";
			return time;
		}
	
		//get percentage(double) from time string
		//ex: 2.30 -> 2.5, 2.45 -> 2.75
		public static double time2Percent(string time)
		{
			if(time == null || time.Length == 0) return 0.0;
			else if(time.IndexOf(".") == -1) return Convert.ToDouble(time);
			else
			{
				time = fixTimeValue(time);
				string[] str = time.Split('.');
				str[1] =  Convert.ToInt32((Convert.ToInt32( str[1] ) * 100 ) / 60) + "";
				if(str[1].Length == 1) return Convert.ToDouble( str[0] +".0"+ str[1]);
				return Convert.ToDouble( str[0] +"."+ str[1]);
			}
		}
	
		//get correct time string from percentage string
		public static string percent2Time(string percent)
		{
			if(percent == null || percent.Length == 0) return "0.0";
			else if(percent.IndexOf(".") == -1) return percent+".0";
			else
			{
				string[] str = percent.Split('.');
				str[1] =  Convert.ToInt32((Convert.ToInt32( str[1] ) * 60 ) / 100) + "";
				if(str[1].Length == 1) return fixTimeValue( str[0] +".0"+ str[1]);
				return fixTimeValue( str[0] +"."+ str[1]);
			}
		}
	
		//get total minute from time string
		//ex: 1.30 --> 90
		public static int time2Minute(string time){
			if(time == null || time.Length == 0) return 0;
			else if( StringLib.indexOfAny(time,".:") == -1 ) return Convert.ToInt32(time) * 60;
			else {
				string[] str = StringLib.SplitByAny(time, ".:");
				return (Convert.ToInt32(str[0]) * 60) + Convert.ToInt32(str[1]);
			}
		}
	
		//get time string from minute
		//ex: 90 -> 1.30
		public static string minute2Time(int minutes, char separator)
		{			
			return minute2Time( minutes ).Replace(".", separator.ToString());
		}
		
		public static string minute2Time(int minutes)
		{
			if(minutes < 10) return fixTimeValue( "0.0"+minutes );
			else if(minutes >= 10 && minutes<60) return fixTimeValue( ("0.") + minutes );
			else if(minutes >= 60)
			{
				int hou = minutes / 60;
				int min = minutes - (hou * 60);
				if(min<10) return fixTimeValue( hou + (".0") + min );
				else return fixTimeValue( "" + hou + "." + min );
			}
			return minutes.ToString();
		}
		
		
		public static string[] getWeekDate(DateTime dat)
		{			
			//get index day of week
			string dayOfWeek = "MonTueWedThuFriSatSun";
			int    dayIndex  = dayOfWeek.IndexOf( dat.ToLongDateString().Substring(0,3) ) / 3;
			if(dayIndex > 0) dayIndex = - dayIndex;
				
			//get max day of current month and previous month
			int MaxDayOfMonth = 31;
			string month30 = ",4,6,9,11,";
			if(month30.IndexOf(","+dat.Month+",") >= 0) MaxDayOfMonth = 30;
			if(dat.Month == 2) MaxDayOfMonth = 28;
			if(dat.Month == 2 && (dat.Year % 4 == 0 || dat.Year % 100 == 0) ) MaxDayOfMonth = 29;
	
			int MaxDayOfPreviousMonth = 31;
			if(month30.IndexOf(","+(dat.Month - 1)+",") >= 0) MaxDayOfPreviousMonth = 30;
			if((dat.Month - 1) == 2) MaxDayOfPreviousMonth = 28;
			if((dat.Month - 1) == 2 && (dat.Year % 4 == 0 || dat.Year % 100 == 0) ) MaxDayOfPreviousMonth = 29;
	
	
			//get day for selected week
			int[]    returnDay	  = new int[7];
			string[] returnDayStr = new string[7];
			int firstIndex = 0;
			for(int i = dayIndex;i< dayIndex + 7;i++)
			{
				returnDay[firstIndex] = (dat.Day + i);
				returnDayStr[firstIndex] = dat.Month + "/" + (dat.Day + i) + "/" + dat.Year;
	
				if(returnDay[firstIndex] > MaxDayOfMonth)
				{
					returnDay[firstIndex] = returnDay[firstIndex] - MaxDayOfMonth;
					returnDayStr[firstIndex] = (dat.Month + 1) + "/" + (returnDay[firstIndex]) + "/" + dat.Year;
					if(dat.Month == 12) returnDayStr[firstIndex] = "1/" + (returnDay[firstIndex]) + "/" + (dat.Year+1);
				}
				if(returnDay[firstIndex] <= 0)
				{
					returnDay[firstIndex] = MaxDayOfPreviousMonth + returnDay[firstIndex];
					returnDayStr[firstIndex] = (dat.Month - 1) + "/" + (returnDay[firstIndex]) + "/" + dat.Year;
					if(dat.Month == 1) returnDayStr[firstIndex] = "12/" + (returnDay[firstIndex]) + "/" + (dat.Year-1);
				}
	
				firstIndex++;
			}
			return returnDayStr;
		}
	
		public static int[] getWeekDateInt(DateTime dat)
		{
			string[] date = getWeekDate(dat);
			int[] returndate = new int[date.Length];
			for(int i=0;i<date.Length;i++)
				returndate[i] = Convert.ToInt16( date[i].Split('/')[1] );
			return returndate;
		}
		
		//get total time of all rows with specific column of a table in dataset.	
		public static string getTotalTime(System.Data.DataSet ds, int tableIndex, int columnIndex)
		{		
			int total = 0;
			if(ds != null && ds.Tables[tableIndex].Rows.Count > 0)
				for(int i=0;i<ds.Tables[tableIndex].Rows.Count;i++)
					total+= time2Minute( ds.Tables[tableIndex].Rows[i][columnIndex].ToString() );
			return minute2Time(total);
			 
		}
		
		//get total time of all rows with specific column of a table in dataset.	
		//with array index of columns and its value to match correlative
		public static string getTotalTime(System.Data.DataSet ds, int tableIndex, int columnIndex,int[] conditionColumnIndex,string[] conditionColumnValue )
		{		
			int total = 0;
			if(ds != null && ds.Tables[tableIndex].Rows.Count > 0)
				for(int i=0;i<ds.Tables[tableIndex].Rows.Count;i++)
				{
					bool isCorrect = true;
					for(int j=0;j<conditionColumnIndex.Length;j++)
						if(ds.Tables[tableIndex].Rows[i][conditionColumnIndex[j]].ToString() != conditionColumnValue[j])
							isCorrect = false;
					
					if(isCorrect)
					total+= time2Minute( ds.Tables[tableIndex].Rows[i][columnIndex].ToString() );
				}
			return minute2Time(total);			 
		}	
	
		//get datetime from date string and time string
		//date: MM/dd/yyy  - time: hh:mm
		public static DateTime getDateTimeFromString(string date, string time){
			if(date.IndexOf("/") == -1 || date.IndexOf("/") == date.LastIndexOf("/") || time.IndexOf(":") == -1)
				return getDate();
			else{
				int mon = Convert.ToInt16(date.Split('/')[0]);
				int day = Convert.ToInt16(date.Split('/')[1]);
				int yea = Convert.ToInt16(date.Split('/')[2]);
				int hou = Convert.ToInt16(time.Split(':')[0]);
				int min = Convert.ToInt16(time.Split(':')[1]);
				return new DateTime(yea,mon,day,hou,min,0,0);
			}
		}
		
		
		//get next date string from passed DateTime
		public static string getNextDate(DateTime dat){
			return dat.AddDays(1).ToString("MM/dd/yyyy");
		}
		
		//get next date string from passed date string
		public static string getNextDate(string dat)
		{
			return getNextDate( DateTime.Parse( dat ) );			
		}
	
		//get previous date string from passed DateTime
		public static string getPreviousDate(DateTime dat)
		{
			return dat.AddDays(-1).ToString("MM/dd/yyyy");
		}
		
		//get previous date string from passed date string
		public static string getPreviousDate(string dat)
		{
			return getPreviousDate( DateTime.Parse( dat ) );
		}
		
		/// <summary>
		/// Compare current date with another date
		/// </summary>
		/// <param name="currentDate"></param>
		/// <param name="DateToCompare"></param>
		/// <returns>0: equal, 1: higher, -1: lower </returns>
		public enum CompareType{ higher=1, equal=0, lower=-1 }
		public static CompareType compareDate( DateTime currentDate, DateTime DateToCompare ){			
			if( currentDate.Year > DateToCompare.Year ) return CompareType.higher;
			if( currentDate.Year < DateToCompare.Year ) return CompareType.lower;
			
			if( currentDate.Month > DateToCompare.Month ) return CompareType.higher;
			if( currentDate.Month < DateToCompare.Month ) return CompareType.lower;
			
			if( currentDate.Day > DateToCompare.Day ) return CompareType.higher;
			if( currentDate.Day < DateToCompare.Day ) return CompareType.lower;
			
			return CompareType.equal;
		}
		
		public static CompareType compareDate( string currentDate, string DateToCompare ){
			return compareDate( DateTime.Parse( currentDate ), DateTime.Parse( DateToCompare ) );
		}

        public static string ToGioNgayString(this DateTime dat)
        {
            return string.Format("{0:HH} giờ {1:mm} ngày {2:dd/MM/yyyy}", dat, dat, dat);
        }

        public static string ToNgayThangNamString(this DateTime dat)
        {
            return string.Format("Ngày {0:dd} tháng {1:MM} năm {2:yyyy}", dat, dat, dat);
        }

        public static string ToThangNamString(this DateTime dat)
        {
            return string.Format("Tháng {1:MM} năm {2:yyyy}", dat, dat);
        }

        public static string ToDMYString(this DateTime dat)
        {
            return dat.ToString("dd/MM/yyyy");
        }
	 }

     
 }
